import {
  fileUploadAddReq,
  fileUploadAll,
  fileUploadReq,
  uploadCheckReq,
} from "@/service/modules/public/public";
// import LocalCache from "@/utils/cache";
import BMF from "browser-md5-file";
import { Toast } from "vant";

let catalog = "jfjl";

/**
 * 文件选择上传
 */
export const iptChange = async (file) => {
  let res = await bmfFile(file);
  return res;
};
// 编码文件
async function bmfFile(file) {
  const bmf = new BMF();
  return new Promise((resolve) => {
    bmf.md5(file, async (err, md5) => {
      console.log("err11111", err);
      let res = await uploadCheck(md5, file);
      resolve(res);
    });
  });
}
const chunkUpload = (chunkList, file, options) => {
  let { md5, chunkSize } = options;
  let reqList = [];
  for (let i = 0; i < chunkList.length; i++) {
    let sliceInfo = {
      sliceIndex: i + 1, // 当前片段的索引
      sliceSize: chunkSize, // 切片的文件分片大小 (就是以多少字节进行分片的，这里是5M)
      totalSize: file.size, //文件大小
      sliceTotal: chunkList.length, // 共有多少分片
    };
    let obj = {
      sliceInfo: sliceInfo,
      file: chunkList[i],
      md5,
      name: file.name,
      catalog,
      size: chunkSize,
      type: file.name.split(".").at(-1),
    };
    reqList.push(fileUploadAddReq(obj));
  }
  return Promise.all(reqList)
    .then(async (result) => {
      // 全部上传成功
      let obj = {
        md5,
        catalog,
        originalFilename: file.name,
        myFilename: file.name,
        archived: 1,
        type: file.name.split(".").at(-1),
      };
      //   合并上传
      let res1 = await fileUploadReq(obj);
      let data = { err: "" };
      if (res1?.status === 200) {
        data = res1.result;
      } else {
        Toast.fail(res1.message)
      }
      return data;
    })
    .catch(() => {});
};
// 检查文件是否存在
const uploadCheck = async (md5, file) => {
  //   上传前检查accessToken
  //   let accessToken = LocalCache.getSession("loginInfo")?.accessToken;
  //   let fl = await islogin(accessToken);
  //   if (!fl) {
  //     // 令牌失效
  //     return "";
  //   } else {
  let params = {
    md5: md5,
    catalog: catalog,
    type: file.name.split(".").at(-1),
  };
  try {
    let res = await uploadCheckReq(params);
    if (res.status === 200) {
      // 文件已存在
      if (res.result.exist) {
        // 文件已存在
        return res.result;
      } else {
        // 文件不存在
        // 切片上传
        const sizeM = file.size / 1024 / 1024;
        if (sizeM > 5) {
          const chunkSize = 5 * 1024 * 1024;
          const options = {
            catalog,
            md5,
            chunkSize,
          };

          let chunkList = [];
          function chunkPush(page = 1) {
            chunkList.push(
              file.slice((page - 1) * chunkSize, page * chunkSize)
            );
            if (page * chunkSize < file.size) {
              chunkPush(page + 1);
            }
          }
          chunkPush();
          let res = chunkUpload(chunkList, file, options);
          return res;
        } else {
          let res = await pushFile(file);
          return res;
        }
      }
    } else {
      Toast.fail(res.message)
    }
  } catch (error) {}
  //   }
};
// 文件一起上传
async function pushFile(file) {
  let params = {
    file,
    catalog,
    myFileName: file.name,
    archived: 1,
  };
  let res = await fileUploadAll(params);
  let obj = {};
  if (res?.status === 200) {
    obj = res?.result;
  } else {
    Toast.fail(res.message)
  }
  return obj;
}

// 文件下载
export async function downLoadFile(params) {
  let res = await fileDownloadReq(params);
  let BLOB = new Blob([res], {
    type: "application/*;charset=utf-8",
  });
  const uA = window.navigator.userAgent;
  const isIE =
    /msie\s|trident\/|edge\//i.test(uA) &&
    !!(
      "uniqueID" in document ||
      "documentMode" in document ||
      "ActiveXObject" in window ||
      "MSInputMethodContext" in window
    );
  if (isIE) {
    // 兼容ie
    navigator.msSaveBlob(BLOB, params.fileName);
  } else {
    let url = window.URL.createObjectURL(BLOB);
    let link = document.createElement("a");
    link.href = url;
    link.target = "_self";
    link.style.display = "none";
    link.setAttribute("download", params.fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  }
  if (res) {
    return true;
  } else {
    return false;
  }
}
